package shardingsphere.demo.strategy;

import java.util.Collection;

import com.alibaba.fastjson.JSON;

import io.shardingsphere.api.ShardingContextHelper;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;

/**
 * HashCodePreciseShardingAlgorithm 哈希取模精确分片算法
 * 
 * @author naah
 * @date 2018-07-26 下午3:33
 * @desc
 */
@Slf4j
public class HashCodePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long>
{
    
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue)
    {
        log.info("availableTargetNames:" + JSON.toJSONString(availableTargetNames) + ",preciseShardingValue:"
            + JSON.toJSONString(shardingValue));
        log.info("待解析的SQL:{}",ShardingContextHelper.getSqlContext());
        // 通过hashcode取模
        int num = (shardingValue.getValue() + "").hashCode() % availableTargetNames.size();
        String[] list = availableTargetNames.toArray(new String[availableTargetNames.size()]);
        if (num <= availableTargetNames.size())
        {
            log.info("return name:" + list[num]);
            return list[num];
        }
        return null;
    }
}
